package cn.fanqinghong.ymcc.mq.listener;

import cn.fanqinghong.ymcc.constants.CourseOrderContants;
import cn.fanqinghong.ymcc.domain.CourseOrder;
import cn.fanqinghong.ymcc.dto.PayDto;
import cn.fanqinghong.ymcc.service.ICourseOrderService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * FAN
 * 2022/7/30  15:34
 */
@Component
@Slf4j
@RocketMQTransactionListener(txProducerGroup = CourseOrderContants.COURSE_ORDER_PRODUCER_GROUP)
public class CourseOrderRocketMqListener implements RocketMQLocalTransactionListener {
    @Autowired
    private ICourseOrderService courseOrderService;
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        log.info("执行本地事务");
        if (o==null) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        try {
            CourseOrder courseOrder = (CourseOrder) o;
            //保存主订单和子订单
            courseOrderService.savaOrderAndItemOrder(courseOrder);
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }

    /**
     * 检查本地事务是否执行成功，检查主订单和子订单是否保存成功
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        log.info("检查本地事务执行是否成功");
        try {
            byte[] payload = (byte[]) message.getPayload();
            String messageStr = new String(payload, StandardCharsets.UTF_8);
            PayDto payDto = JSONObject.parseObject(messageStr, PayDto.class);
            //通过订单号查询数据
            CourseOrder courseOrder = courseOrderService.selectOrderAndItemOrder(payDto.getOrderNo());
            //得到null表示本地事务执行失败，不为null表示本地事务执行成功
            return courseOrder == null?RocketMQLocalTransactionState.ROLLBACK:RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }
}
